//
//  categoriesViewController.m
//  NewIMGII
//
//  Created by 步遴 李 on 12-6-11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "categoriesViewController.h"
#import "AFNetworking.h"
#import "CateListViewController.h"

@implementation categoriesViewController
@synthesize categories,category,catstable;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
     NSLog(@"nv is %@",self.navigationController);
    self.navigationItem.title = @"Imgii视觉杂志";
    appdelegate = [[UIApplication sharedApplication]delegate];
    context = [appdelegate managedObjectContext];
    entity =[NSEntityDescription entityForName:@"Category" inManagedObjectContext:context];
    cdrequest = [[NSFetchRequest alloc]init];
    [cdrequest setPredicate:pre];
    [cdrequest setEntity:entity];
    self.categories = [context executeFetchRequest:cdrequest error:&error];
    categoriesCount = [self.categories count];
    [cdrequest release];
    [self refreshCategorys];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(void)refreshCategorys
{
    NSString *postUrl = [[NSString alloc]initWithFormat:@"http://www.imgii.com/api/get_category_index"];    
    NSURL *url = [NSURL URLWithString:postUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSArray *categoriesArry = [JSON valueForKeyPath:@"categories"];
        for (NSInteger i =0; i < [categoriesArry count]; i++) {
            cdrequest = [[NSFetchRequest alloc]init];
            entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:context];
            [cdrequest setEntity:entity];
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"(catid = %@)",[[categoriesArry objectAtIndex:i] valueForKey:@"id"]];
            [cdrequest setPredicate:pred];
            NSManagedObject *catContext = nil;    
            NSArray *catlist = [context executeFetchRequest:cdrequest error:&error];
            if (catlist == nil) {
                NSLog(@"error because of %@",[error localizedDescription]);
            }
            NSLog(@"blogs count = %d",[catlist count]);
            if([catlist count] >0)
            {
                catContext = [catlist objectAtIndex:0];
                
            }else
            {
                catContext = [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:context];
            }
            [catContext setValue:[[categoriesArry objectAtIndex:i] valueForKey:@"id"] forKey:@"catid"];
            [catContext setValue:[[categoriesArry objectAtIndex:i] valueForKey:@"parent"] forKey:@"parent"];
            [catContext setValue:[[categoriesArry objectAtIndex:i] valueForKey:@"title"] forKey:@"title"];
            [catContext setValue:[[categoriesArry objectAtIndex:i] valueForKey:@"parent"] forKey:@"parent"];

            [cdrequest release];

        }
        [context save:&error];
        cdrequest = [[NSFetchRequest alloc]init];
        [cdrequest setEntity:entity];
        self.categories = [context executeFetchRequest:cdrequest error:&error];
        [cdrequest release];
        [self.catstable reloadData];
    } failure:nil];
    [operation start];
}
#pragma mark-
#pragma mark Table View Delegate Methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.category = [self.categories objectAtIndex:[indexPath row]];
   
    self.navigationItem.title = @"文章分类";
    CateListViewController *catlist = [[CateListViewController alloc]initWithNibName:@"CateListViewController" bundle:nil];
    NSString *TTitle = [[NSString alloc]initWithFormat:@"*%@*",self.category.title];
    catlist.catTitle = TTitle;
    [TTitle release];
    TTitle = nil;
    [self.navigationController pushViewController:catlist animated:YES];
    [catlist release];
}
#pragma mark-
#pragma mark Table View Data Source Methods 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.categories count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleIdent = @"simpleIdent";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleIdent];
    
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleIdent]autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
    }

    self.category = [self.categories objectAtIndex:[indexPath row]];
    cell.textLabel.text = self.category.title;

    return cell;
}

@end
